<template>
  <div class="container">
    <div class="row">
      <div class="col-md-2">
        <el-table
          :data="tableData"
          class="w-100"
          max-height="700px"
          row-key="id"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          default-expand-all
          :show-header="false"
          @row-click="handleSelect"
        >
          <el-table-column label="部门">
            <template #default="{ row }">
              <a href="javascript:void(0)" @click="handleSelect(row)">
                <span class="text-primary">{{ row.name }}</span>
                <span class="text-muted ms-2">({{ row.engineerCount }})</span>
              </a>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="col-md-4">
        <div class="container">
          <div class="row">
            <div class="col-md-12">
              <h4 class="text-gray-600">{{ selectedDeptName }}</h4>
            </div>
            <div v-for="engineer in engineers" :key="engineer.id" class="col-md-4">
              <a href="javascript:void(0)" @click="handleEngineerSelect(engineer)">
                <span class="fw-bold fs-4 text-gray-600">{{ engineer.name }}</span>
                <KTIcon
                  :icon-name="roleSettings[engineer.role || ''].icon"
                  :icon-class="`fs-5 text-${roleSettings[engineer.role || ''].color} ms-2`"
                />
                <span :class="`badge badge-light-${roleSettings[engineer.role || ''].color} ms-1`">
                  {{ roleSettings[engineer.role || ''].name }}
                </span>
              </a>
            </div>
          </div>
          <div class="row mt-4">
            <div class="col-md-12">
              <h4 class="text-gray-600">{{ selectedEngineerName }} - 已绑定账号</h4>
            </div>
            <div class="col-md-12">
              <el-table
                :data="emails"
                class="w-100"
                max-height="500px"
                stripe
                row-key="id"
                :show-header="false"
              >
                <el-table-column width="40">
                  <template #default="{ $index }">
                    <span class="fs-6 text-gray-500">{{ $index + 1 }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="账号">
                  <template #default="{ row }">
                    <span class="fs-6 text-gray-500">name: </span>
                    <span class="fs-5 ms-2 text-gray-600">{{ row.authorFullname }}</span>
                    <a href="javascript:void(0)" class="ms-1" @click="handleRemoveEmail(row.id)">
                      <i class="fa fa-close fs-6 text-danger"></i>
                    </a>
                    <br />
                    <span class="fs-6 text-gray-500">email: </span>
                    <span class="fs-5 ms-2 text-gray-600">{{ row.authorEmail }}</span>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </div>
      </div>
      <div class="col-md-6">
        <div class="container">
          <div class="row">
            <div class="col-md-12">
              <h4 class="text-gray-600">所有日志中的账号:</h4>
            </div>
            <div class="col-md-12">
              <el-input
                v-model="searchQuery"
                placeholder="搜索作者姓名、邮箱或工程师姓名"
                clearable
                class="mb-3"
              ></el-input>
              <el-table
                :data="filteredAuthors"
                class="w-100"
                max-height="600px"
                stripe
                row-key="id"
              >
                <el-table-column label="序号" min-width="40" align="center">
                  <template #default="{ $index }">
                    <span class="fs-6 text-gray-500">{{ $index + 1 }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="账号" min-width="200">
                  <template #default="{ row }">
                    <span class="fs-6 text-gray-500">name: </span>
                    <span class="fs-5 ms-2 text-gray-600">{{ row.authorFullname }}</span>
                    <a
                      href="javascript:void(0)"
                      class="ms-1"
                      @click="handleAddEmail(row.authorFullname, row.authorEmail)"
                    >
                      <i class="fa fa-plus fs-6 text-success"></i>
                    </a>
                    <br />
                    <span class="fs-6 text-gray-500">email: </span>
                    <span class="fs-5 ms-2 text-gray-600">{{ row.authorEmail }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="工程师" min-width="60" align="center">
                  <template #default="{ row }">
                    <span class="fs-6 text-gray-500">{{ row.engineerName || '' }}</span>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue';
import { departmentService } from '@/services/business/department.service';
import { engineerService } from '@/services/business/engineer.service';
import type { DepartmentTreeDTO } from '@/types/business/department';
import type { Engineer } from '@/types/business/engineer';
import type { EngineerEmail } from '@/types/business/engineer';
import { roleSettings } from '@/utils/roleUtils';
import KTIcon from '@/core/helpers/kt-icon/KTIcon.vue';
import type { AuthorInfo } from '@/types/business/engineer';
import { computed } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';

const tableData = ref<DepartmentTreeDTO[]>([]);

function addLevelsAndDescriptions(
  nodes: DepartmentTreeDTO[],
  currentLevel: number,
): DepartmentTreeDTO[] {
  return nodes.map((node) => ({
    ...node,
    level: `${currentLevel}级`,
    description: `这是${node.name}`,
    children: addLevelsAndDescriptions(node.children, currentLevel + 1),
  }));
}

const fetchDepartmentTree = async () => {
  try {
    const rawData = await departmentService.getDepartmentTree();
    tableData.value = addLevelsAndDescriptions(rawData, 1);
  } catch (err) {
    console.error('Failed to fetch department tree:', err);
  }
};

// Engineer 接口已在 types 中定义
const selectedDeptId = ref('');
const selectedDeptName = ref('');
const engineers = ref<Engineer[]>([]);

const handleSelect = (row: DepartmentTreeDTO) => {
  selectedDeptId.value = row.id;
  selectedDeptName.value = row.name;
  fetchEngineers();
};

const fetchEngineers = async () => {
  if (!selectedDeptId.value) return;
  try {
    engineers.value = await engineerService.getEngineersByDept(selectedDeptId.value);
  } catch (err) {
    console.error('Failed to fetch engineers:', err);
  }
};

const selectedEngineerId = ref('');
const emails = ref<EngineerEmail[]>([]);
const selectedEngineerName = ref('');

const handleEngineerSelect = (row: Engineer) => {
  selectedEngineerId.value = row.id;
  selectedEngineerName.value = row.name;
  fetchEmails();
};

const fetchEmails = async () => {
  if (!selectedEngineerId.value) return;
  try {
    emails.value = await engineerService.getEmailsByEngineerId(selectedEngineerId.value);
  } catch (err) {
    console.error('Failed to fetch emails:', err);
  }
};

const handleRemoveEmail = (id: string) => {
  ElMessageBox.confirm('确定移除该账号吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      await engineerService.removeEmail(id);
      fetchEmails();
      fetchAuthors();
    } catch (err) {
      console.error('Failed to remove email:', err);
      ElMessage.error('移除失败');
    }
  });
  fetchEmails();
};

const handleAddEmail = (authorFullname: string, authorEmail: string) => {
  ElMessageBox.confirm(`确定添加该账号给${selectedEngineerName.value}吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      await engineerService.addEmail(authorFullname, authorEmail, selectedEngineerId.value);
      fetchEmails();
      fetchAuthors();
    } catch (err) {
      console.error('Failed to add email:', err);
      ElMessage.error('添加失败');
    }
  });
};

watch(engineers, () => {
  emails.value = [];
  selectedEngineerName.value = '';
  selectedEngineerId.value = '';
});

onMounted(fetchDepartmentTree);

const authors = ref<AuthorInfo[]>([]);
const fetchAuthors = async () => {
  authors.value = await engineerService.getDistinctAuthors();
};
onMounted(() => {
  fetchAuthors();
});

const searchQuery = ref('');

const filteredAuthors = computed(() => {
  const query = searchQuery.value.toLowerCase();
  if (query.trim() === '' && searchQuery.value !== '') {
    return authors.value.filter(
      (author) =>
        !author.engineerName || author.engineerName === '' || author.engineerName === '未知工程师',
    );
  } else if (query === '') {
    return authors.value;
  } else {
    return authors.value.filter((author) => {
      return (
        author.authorFullname.toLowerCase().includes(query) ||
        author.authorEmail.toLowerCase().includes(query) ||
        (author.engineerName && author.engineerName.toLowerCase().includes(query))
      );
    });
  }
});
</script>
